<script setup lang="ts">
import { getQuestionInfo, getLatestQuestions } from '@/api/subject';
import type { Choice, Question } from '@/api/subject/type';
import { onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import ChoiceAnswer from './components/ChoiceAnswer.vue';
import JudgeAnswer from './components/JudgeAnswer.vue';
import EssayAnswer from './components/EssayAnswer.vue';
import { getAnalysis } from '@/api/code/codeCompletion';
import MarkdownRenderer from '@/views/home/code/components/MarkdownRenderer.vue';
import { showToast } from 'vant';

const route = useRoute();
const router = useRouter();

const question = ref({} as Question);
const answer = ref<string | string[]>([]);  
const choice = ref({} as Choice);
const title = ref('');
const isFinish = ref(false);
const isRight = ref(false);
const analysis = ref('AI思考中...');
const questionIdList = ref<string[]>([]);
const currentIndex = ref(0);
const loading = ref(true);

const toSubjectHome = () => {
  router.push({ name: 'SubjectHome', query: { id: route.query.subjectId } });
};

const fetchLatestQuestionIds = async () => {
  const subjectId = Array.isArray(route.query.subjectId)
    ? route.query.subjectId[0]
    : route.query.subjectId
  if (!subjectId) {
    console.error('未获取到 subjectId');
    return;
  }
  try {
    const res = await getLatestQuestions(subjectId);
    const questions = res.data && Array.isArray(res.data) ? res.data : res;
    if (!Array.isArray(questions)) {
      console.error('返回数据格式错误，不是数组：', questions);
      return;
    }
    questionIdList.value = questions.map((q: any) => q.id.toString());
    const currentIdRaw = Array.isArray(route.query.id)
      ? route.query.id[0]
      : route.query.id;
    currentIndex.value = questionIdList.value.findIndex(id => id === currentIdRaw);
  } catch (error) {
    console.error('获取题目列表失败', error);
    showToast('获取题目列表失败');
  }
};

const fetchQuestionInfo = async (id: string) => {
  try {
    loading.value = true;
    const res = await getQuestionInfo(id);
    question.value = res.data;
    // 重置答题状态
    answer.value = question.value.type === "Choice" && question.value.answer.includes(",") ? [] : '';  // 初始化答案
    isFinish.value = false;
    analysis.value = 'AI思考中...';
    if (question.value.type === "Choice") {
      choice.value = JSON.parse(question.value.answer);
      title.value = choice.value.isMultiple ? '多选题' : '单选题';
    } else if (question.value.type === "Judge") {
      title.value = '判断题';
      try {
        const parsedAnswer = JSON.parse(question.value.answer);
        question.value.answer = parsedAnswer.correctAnswer === "true" ? "正确" : "错误";
      } catch (error) {
        console.error('Judge答案解析失败', error);
      }
    } else if (question.value.type === "Blank") {
      title.value = '填空题';
    } else {
      title.value = '简答题';
    }
  } catch (error) {
    console.error('获取题目信息失败', error);
    showToast('获取题目信息失败');
  } finally {
    loading.value = false;
  }
};

onMounted(async () => {
  await fetchLatestQuestionIds();
  const currentId = Array.isArray(route.query.id)
    ? route.query.id[0]
    : route.query.id;
  if (currentId) {
    await fetchQuestionInfo(currentId);
  }
});

watch(currentIndex, async () => {
  const currentId = questionIdList.value[currentIndex.value];
  if (currentId) {
    answer.value = question.value.type === "Choice" && question.value.answer.includes(",") ? [] : ''; // 清空答案
    await fetchQuestionInfo(currentId); 
  }
});

const goLast = async () => {
  if (currentIndex.value > 0) {
    currentIndex.value--; 
    const lastId = questionIdList.value[currentIndex.value]; 
    router.push({ name: route.name as string, query: { subjectId: route.query.subjectId, id: lastId } });
  }
};

const goNext = () => {
  if (currentIndex.value < questionIdList.value.length - 1) {
    currentIndex.value++; 
    const nextId = questionIdList.value[currentIndex.value];
    router.push({ name: route.name as string, query: { subjectId: route.query.subjectId, id: nextId } });
  }
};

const submitAnswer = async () => {
  if (!answer.value || (Array.isArray(answer.value) && answer.value.length === 0)) {
    showToast('请先作答');
    return;
  }
  
  isFinish.value = true;
  if (question.value.type === 'Choice') {
    if (choice.value.isMultiple) {
      const userAnswerArray = answer.value as string[];
      const correctAnswerArray = choice.value.correctAnswer.map((index: number) => choice.value.options[index]);
      
      // 检查答案是否完全匹配
      isRight.value = 
        userAnswerArray.length === correctAnswerArray.length && 
        userAnswerArray.every(item => correctAnswerArray.includes(item)) && 
        correctAnswerArray.every(item => userAnswerArray.includes(item));
    } else {
      // 单选题
      const correctAnswerIndex = choice.value.correctAnswer[0];
      const correctAnswer = choice.value.options[correctAnswerIndex];
      isRight.value = answer.value === correctAnswer;
    }
  } else if (question.value.type === 'Judge') {
    const userAnswer = answer.value === 'true' ? '正确' : answer.value === 'false' ? '错误' : answer.value;
    isRight.value = userAnswer === question.value.answer;
  } else {
    // 填空题和简答题不自动判断对错，需要学生自检
  }
  
  try {
    let displayAnswer = '';
    if (Array.isArray(answer.value)) {
      displayAnswer = answer.value.join(', ');
    } else {
      displayAnswer = answer.value;
    }
    
    analysis.value = '正在生成AI解析...';
    const aiAnalysis = await getAnalysis(question.value.title, displayAnswer);
    analysis.value = aiAnalysis;
  } catch (error) {
    analysis.value = '很抱歉，AI解析生成失败。';
    console.error('AI解析生成失败:', error);
  }
};
</script>

<template>
  <div class="question-answer">
    <div class="page-header">
      <div class="back-action" @click="toSubjectHome">
        <van-icon name="arrow-left" />
        <span>返回题目集</span>
      </div>
      <h1 class="page-title">答题练习</h1>
      <div class="question-navigation">
        <span class="question-count">当前第 {{ currentIndex + 1 }}/{{ questionIdList.length }} 题</span>
        <div class="nav-buttons">
          <button class="nav-button" @click="goLast" :disabled="currentIndex === 0">
            <van-icon name="arrow-left" />
            <span>上一题</span>
          </button>
          <button class="nav-button" @click="goNext" :disabled="currentIndex === questionIdList.length - 1">
            <span>下一题</span>
            <van-icon name="arrow" />
          </button>
        </div>
      </div>
    </div>
    
    <div class="question-content">
      <van-skeleton title :row="6" :loading="loading" v-if="loading" />
      
      <template v-else>
        <div class="question-card">
          <div class="question-header">
            <div class="question-tags">
              <div class="question-tag">{{ title }}</div>
            </div>
            <div class="question-title">{{ question.title }}</div>
          </div>
          
          <div class="question-body">
            <div class="answer-area">
              <template v-if="question.type === 'Choice'">
                <ChoiceAnswer v-model="answer" :choice="choice" :disabled="isFinish" />
              </template>
              <template v-else-if="question.type === 'Judge'">
                <JudgeAnswer v-model="answer" :disabled="isFinish" />
              </template>
              <template v-else>
                <EssayAnswer v-model="answer" :disabled="isFinish" />
              </template>
            </div>
          </div>
          
          <div class="question-footer" v-if="!isFinish">
            <button class="submit-button" @click="submitAnswer">提交答案</button>
          </div>
        </div>
        
        <div class="answer-result" v-if="isFinish">
          <div class="result-header">
            <div class="result-status" :class="{ 'correct': isRight, 'incorrect': question.type !== 'Blank' && question.type !== 'Essay' && !isRight }">
              <van-icon :name="isRight ? 'success' : 'cross'" v-if="question.type !== 'Blank' && question.type !== 'Essay'" />
              <span>{{ isRight ? '回答正确' : (question.type !== 'Blank' && question.type !== 'Essay') ? '回答错误' : '已提交答案' }}</span>
            </div>
          </div>
          
          <div class="result-content">
            <div class="result-section">
              <h3>你的答案</h3>
              <div class="answer-display">
                <template v-if="question.type === 'Judge'">
                  {{ answer === 'true' ? '正确' : answer === 'false' ? '错误' : answer }}
                </template>
                <template v-else-if="question.type === 'Choice' && choice.isMultiple">
                  {{ Array.isArray(answer) ? answer.join(', ') : answer }}
                </template>
                <template v-else>
                  {{ answer }}
                </template>
              </div>
            </div>
            
            <div class="result-section" v-if="question.type !== 'Blank' && question.type !== 'Essay'">
              <h3>正确答案</h3>
              <div class="answer-display correct">
                <template v-if="question.type === 'Choice'">
                  <template v-if="choice.isMultiple">
                    {{ choice.correctAnswer.map(index => choice.options[index]).join(', ') }}
                  </template>
                  <template v-else>
                    {{ choice.options[choice.correctAnswer[0]] }}
                  </template>
                </template>
                <template v-else>
                  {{ question.answer }}
                </template>
              </div>
            </div>
            
            <div class="result-section analysis">
              <h3>AI解析</h3>
              <div class="analysis-content" v-if="analysis !== 'AI思考中...' && analysis !== '正在生成AI解析...'">
                <MarkdownRenderer :content="analysis" />
              </div>
              <div class="analysis-loading" v-else>
                <van-loading type="spinner" size="24px" />
                <span>{{ analysis }}</span>
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.question-answer {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 16px;
  
  .page-header {
    margin-bottom: 24px;
    
    .back-action {
      display: inline-flex;
      align-items: center;
      gap: 6px;
      color: #606266;
      cursor: pointer;
      padding: 8px 0;
      font-size: 14px;
      margin-bottom: 8px;
      
      &:hover {
        color: #409eff;
      }
    }
    
    .page-title {
      font-size: 24px;
      font-weight: 600;
      color: #303133;
      margin: 0 0 16px 0;
    }
    
    .question-navigation {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .question-count {
        font-size: 14px;
        color: #606266;
      }
      
      .nav-buttons {
        display: flex;
        gap: 12px;
        
        .nav-button {
          display: flex;
          align-items: center;
          gap: 6px;
          height: 36px;
          padding: 0 16px;
          border-radius: 18px;
          background-color: #fff;
          border: 1px solid #dcdfe6;
          color: #606266;
          font-size: 14px;
          cursor: pointer;
          
          &:hover:not(:disabled) {
            color: #409eff;
            border-color: #c6e2ff;
            background-color: #ecf5ff;
          }
          
          &:disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }
        }
      }
    }
  }
  
  .question-content {
    .question-card {
      background-color: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      margin-bottom: 24px;
      
      .question-header {
        padding: 20px 24px;
        border-bottom: 1px solid #ebeef5;
        
        .question-tags {
          margin-bottom: 16px;
          
          .question-tag {
            display: inline-block;
            padding: 6px 12px;
            background-color: #ecf5ff;
            color: #409eff;
            border-radius: 4px;
            font-size: 14px;
            font-weight: 500;
          }
        }
        
        .question-title {
          font-size: 16px;
          line-height: 1.6;
          color: #303133;
          font-weight: 500;
        }
      }
      
      .question-body {
        padding: 24px;
        
        .answer-area {
          // 样式将由组件提供
        }
      }
      
      .question-footer {
        padding: 16px 24px;
        border-top: 1px solid #ebeef5;
        display: flex;
        justify-content: center;
        
        .submit-button {
          height: 40px;
          padding: 0 24px;
          border-radius: 20px;
          background-color: #409eff;
          border: none;
          color: white;
          font-size: 16px;
          font-weight: 500;
          cursor: pointer;
          transition: background-color 0.2s;
          
          &:hover {
            background-color: #66b1ff;
          }
        }
      }
    }
    
    .answer-result {
      background-color: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      
      .result-header {
        padding: 16px 24px;
        border-bottom: 1px solid #ebeef5;
        
        .result-status {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          padding: 8px 16px;
          border-radius: 4px;
          font-weight: 500;
          
          &.correct {
            background-color: #f0f9eb;
            color: #67c23a;
          }
          
          &.incorrect {
            background-color: #fef0f0;
            color: #f56c6c;
          }
          
          &:not(.correct):not(.incorrect) {
            background-color: #ecf5ff;
            color: #409eff;
          }
        }
      }
      
      .result-content {
        padding: 20px 24px;
        
        .result-section {
          margin-bottom: 24px;
          
          h3 {
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            margin: 0 0 12px 0;
          }
          
          .answer-display {
            padding: 12px 16px;
            background-color: #f5f7fa;
            border-radius: 4px;
            color: #606266;
            
            &.correct {
              background-color: #f0f9eb;
              color: #67c23a;
            }
            
            &.incorrect {
              background-color: #fef0f0;
              color: #f56c6c;
            }
          }
          
          &.analysis {
            .analysis-content {
              background-color: #f8f9fb;
              border-radius: 4px;
              padding: 16px;
            }
            
            .analysis-loading {
              display: flex;
              align-items: center;
              gap: 12px;
              padding: 24px;
              justify-content: center;
              color: #909399;
            }
          }
        }
      }
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .question-navigation {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    
    .nav-buttons {
      width: 100%;
      
      .nav-button {
        flex: 1;
        justify-content: center;
      }
    }
  }
}
</style>
